package com.yjt.common.exceptions;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author 曾智平
 * @ClassName: AuthExceptionEntryPoint
 * @Description: 认证token失效异常处理
 * @date 2021/9/27 10:44
 */
@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException)  {
        Throwable cause = authException.getCause();
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if (cause instanceof InvalidTokenException) {
                JSONObject resultObject = new JSONObject();
                resultObject.put("code",-200);
                resultObject.put("message","token已失效,请重新登录");
                response.getWriter().write(resultObject.toJSONString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
